import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:trip_flutter/controller/travel_tab_controller.dart';
import 'package:trip_flutter/widget/loading_container.dart';
import 'package:trip_flutter/widget/travel_item_widget.dart';

///旅拍列表页
class TravelTabPage extends StatefulWidget {
  final String groupChannelCode;

  const TravelTabPage({super.key, required this.groupChannelCode});

  @override
  State<TravelTabPage> createState() => _TravelTabPageState();
}

class _TravelTabPageState extends State<TravelTabPage>
    with AutomaticKeepAliveClientMixin {
  late TravelTabController controller;
  get _gridView => MasonryGridView.count(
    controller: controller.scrollController,
    crossAxisCount: 2,
    itemCount: controller.travelItems.length,
    itemBuilder: ((BuildContext context, int index) =>
        TravelItemWidget(index: index, item: controller.travelItems[index])),
  );

  @override
  void initState() {
    super.initState();
    controller = Get.put(
      // 注意默认单例模式，所以需要通过tag指定唯一性
      TravelTabController(groupChannelCode: widget.groupChannelCode),
      tag: widget.groupChannelCode,
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(body: _obx);
  }

  @override
  bool get wantKeepAlive => true;

  get _obx => Obx(
    () => LoadingContainer(
      isLoading: controller.loading.value,
      child: RefreshIndicator(
        color: Colors.blue,
        onRefresh: _handleRefresh,
        child: MediaQuery.removePadding(
          removeTop: true,
          context: context,
          child: _gridView,
        ),
      ),
    ),
  );

  // 与_obx等价,和Obx不同的是,GetX更细力度的控制状态的更新;但通常用于监听1个GetXController的状态改变
  get _getX => GetX<TravelTabController>(
    builder: (controller) {
      return LoadingContainer(
        isLoading: controller.loading.value,
        child: RefreshIndicator(
          color: Colors.blue,
          onRefresh: _handleRefresh,
          child: MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: _gridView,
          ),
        ),
      );
    },
    init: controller,
  );

  Future<void> _handleRefresh() async {
    await controller.loadData();
    return;
  }
}
